<template>
  <ul ref="myElFromRef" class="list-from" :style="listStyle">
    <slot></slot>
  </ul>
</template>

<script setup lang="ts">
  import { useThrottleFn } from '@vueuse/core';
  import scss from '@/styles/module/export.module.scss';

  const props = defineProps({
    /** label宽度 */
    labelWidth: { type: Number, default: 0 },
    /** item宽度 */
    itemWidth: { type: Number, default: 0 },
    /** item宽度 */
    itemMaxWidth: { type: Number, default: 0 },
    /** 右边距 */
    rightSpace: { type: Number, default: -1 },
    /** 下边距 */
    bottomSpace: { type: Number, default: -1 },
  });
  defineSlots<{
    /** 主体内容 */
    default: () => void;
  }>();
  const isShow = ref(false);
  const myElFromRef = ref<HTMLUListElement | null>(null);
  const globalSize = computed(() => useGlobalStore().globalSize);
  const newLabelWidth = computed(() => (props.labelWidth > 0 ? props.labelWidth : globalSize.value === 'small' ? 48 : 56));
  const newItemWidth = computed(() => (props.itemWidth > 100 ? props.itemWidth : globalSize.value === 'small' ? 280 : 320));
  const newItemMaxWidth = computed(() => (props.itemMaxWidth > 0 ? `${props.itemMaxWidth}px` : '100%'));
  const newRightSpace = computed(() => (props.rightSpace >= 0 ? `${props.rightSpace}px` : 'calc(var(--my-change-base8-4x-space-width) + 8px)'));
  const listStyle = computed(() => {
    const style = {
      '--list-from-label-width': `${newLabelWidth.value}px`,
      '--list-from-item-width': `${newItemWidth.value}px`,
      '--list-from-item-max-width': newItemMaxWidth.value,
      '--list-from-right-space': newRightSpace.value,
      '--list-from-bottom-space': props.bottomSpace >= 0 ? `${props.bottomSpace}px` : 'var(--my-change-base8-4x-space-width)',
      'grid-template-columns': `repeat(auto-fill,minmax(min(100%, ${newItemWidth.value}px), 1fr))`,
    };
    return style;
  });
  const myObserver = new ResizeObserver(
    useThrottleFn(() => {
      const dom = (myElFromRef.value && myElFromRef.value.querySelector('.list-from-item')) || false;
      isShow.value = Boolean(dom && (myElFromRef.value?.clientHeight || 500) > dom.clientHeight * 2 - parseInt(String(scss.appPagePadding)));
    }, 50)
  );
  onMounted(() => {
    if (myElFromRef.value) {
      const dom = myElFromRef.value?.querySelector('.list-from-item');
      isShow.value = Boolean(dom && (myElFromRef.value?.clientHeight || 500) > dom.clientHeight * 2 - parseInt(String(scss.appPagePadding)));
      myElFromRef.value && myObserver.observe(myElFromRef.value);
    }
  });

  onUnmounted(() => {
    myObserver.disconnect();
  });
</script>

<style lang="scss" scoped>
  .list-from {
    display: grid;
    gap: var(--list-from-bottom-space) var(--list-from-right-space);
    width: 100%;
  }
</style>
